<template>
  <div>
    <BasicTable @register="registerTable" @fetch-success="onFetchSuccess" ref="tableRef">
      <template #toolbar v-if="!teamGroupsSelete">
        <a-button type="primary" @click="handleCreate" v-if="hasPermission(['bpm:model:create'])">
          新增
        </a-button>
      </template>
      <template #swicth="{ record }">
        <Switch
          v-if="record.processDefinition"
          :checked="record.processDefinition && record.processDefinition.suspensionState"
          :checked-value="1"
          :un-checked-value="2"
          @change="SwitchChange(record)"
        />
      </template>
      <template #status="{ record }">
        <div
          v-if="record.status === null || record.status === 0"
          style="
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background-color: chartreuse;
            margin: 0 auto;
            box-shadow: 0 0 2px 2px #ccc;
          "
        ></div>
        <div
          v-else
          style="
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background-color: red;
            margin: 0 auto;
            box-shadow: 0 0 3px 3px #ccc;
          "
        ></div>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              label: '删除',
              icon: 'ant-design:delete-outlined',
              color: 'error',
              ifShow: hasPermission(['bpm:model:delete']),
              popConfirm: {
                title: '是否确认删除',
                confirm: handleDelete.bind(null, record),
              },
            },
          ]"
          :dropDownActions="[
            {
              label: '分配表单',
              icon: 'clarity:note-edit-line',
              onClick: handleEdit.bind(null, record),
              ifShow: hasPermission(['bpm:model:update']),
            },
            {
              label: '设计流程',
              icon: 'clarity:note-edit-line',
              onClick: handleDesign.bind(null, record),
              ifShow: hasPermission(['bpm:model:designProcess']),
            },
            {
              label: '分配规则',
              icon: 'clarity:note-edit-line',
              onClick: handleAssignJob.bind(null, record),
              ifShow: hasPermission(['bpm:task-assign-rule:create']),
            },
            {
              label: ' 发布流程',
              icon: 'clarity:note-edit-line',
              popConfirm: {
                title: '是否部署该流程！！',
                confirm: handleRelease.bind(null, record),
              },
              ifShow: hasPermission(['bpm:model:deploy']),
            },
          ]"
        />
      </template>
    </BasicTable>
    <Drawer @register="registerDrawer" @success="handleSuccess" :type="type" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, reactive, toRefs, unref, ref } from 'vue';
  import { usePermission } from '/@/hooks/web/usePermission';
  import { BasicTable, useTable, TableAction, TableActionType } from '/@/components/Table';
  import {
    modeList,
    modelAdd,
    modelEdit,
    modelDelete,
    modelArrangeAdd,
    modelState,
  } from '/@/api/backs/workFlow/form';
  import { useDrawer } from '/@/components/Drawer';
  import { useGo } from '/@/hooks/web/usePage';
  import Drawer from './components/Drawer.vue';
  import { Switch, message } from 'ant-design-vue';

  import { columns, searchFormSchema } from './components/tableData';

  export default defineComponent({
    name: 'MenuManagement',
    components: { BasicTable, Drawer, TableAction, Switch },
    props: {
      teamGroupsSelete: {
        type: Boolean,
        default: false,
      },
    },
    setup(props) {
      const { hasPermission } = usePermission();
      const go = useGo();
      const tableRef = ref<Nullable<TableActionType>>(null);
      const getTableAction = () => {
        const tableAction = unref(tableRef);
        if (!tableAction) {
          throw new Error('tableAction is null');
        }
        return tableAction;
      };

      const [registerDrawer, { openDrawer, closeDrawer }] = useDrawer();
      const [registerTable, { reload, setSelectedRowKeys }] = useTable({
        title: '表单模型列表',
        api: modeList,
        columns,
        formConfig: {
          labelWidth: 100,
          schemas: searchFormSchema,
        },
        useSearchForm: !props.teamGroupsSelete,
        showTableSetting: !props.teamGroupsSelete,
        // rowSelection: props.teamGroupsSelete,
        actionColumn: {
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          // fixed: 'right',
          width: 200,
          // ellipsis:true
        },
      });
      const getSelectRowList = () => {
        return getTableAction().getSelectRows();
      };
      const setSelectedRowKeyList = (arr) => {
        setSelectedRowKeys(arr);
      };
      const data: any = reactive({
        type: 'add',
        // powerInfoList:[],
      });
      //开启关闭
      const SwitchChange = async (record: Recordable) => {
        console.log('-------------', record);

        try {
          let state;
          if (record.processDefinition && record.processDefinition.suspensionState) {
            state = record.processDefinition.suspensionState == 1 ? 2 : 1;
          }

          await modelState({ id: record.id, state: state });
          reload();
        } catch (error) {}
      };
      //设计流程
      function handleDesign(record: Recordable) {
        go('/workFlowManage/WorkFlow/modelDesign/' + record.id);
      }
      //分配规则
      function handleAssignJob(record: Recordable) {
        go('/workFlowManage/WorkFlow/modelAllocation/' + record.id);
      }
      //发布流程
      const handleRelease = async (record: Recordable) => {
        try {
          await modelArrangeAdd({ id: record.id });
          message.success('发布成功！');
          reload();
        } catch (error) {}
      };
      //流程定义
      function handleDefinition(record: Recordable) {
        go('/workFlowManage/WorkFlow/modelDefine/' + record.key);
      }
      //编辑
      const handleEditSuccess = async (formData) => {
        let params = { ...formData };
        try {
          await modelEdit(params);
          message.success('修改成功！');
          closeDrawer();
          reload();
        } catch (error) {}
      };
      //新增
      const handleAddSuccess = async (formData) => {
        let params = { ...formData };
        try {
          await modelAdd(params);
          message.success('新增成功！');
          closeDrawer();
          reload();
        } catch (error) {}
      };
      function handleCreate() {
        openDrawer(true, {
          isUpdate: false,
        });
        data.type = 'add';
      }

      function handleEdit(record: Recordable) {
        openDrawer(true, {
          record,
          isUpdate: true,
        });
        data.type = 'edit';
      }
      //删除
      const handleDelete = async (record: Recordable) => {
        try {
          await modelDelete({ id: record.id });
          message.success('删除成功！');
          reload();
        } catch (error) {}
      };

      function handleSuccess(formData) {
        switch (data.type) {
          case 'add':
            handleAddSuccess(formData);
            break;
          case 'edit':
            handleEditSuccess(formData);
            break;
        }
      }

      function onFetchSuccess() {}

      return {
        ...toRefs(data),
        tableRef,
        registerTable,
        registerDrawer,
        handleCreate,
        handleEdit,
        handleDelete,
        handleSuccess,
        onFetchSuccess,
        getSelectRowList,
        setSelectedRowKeyList,
        handleDesign,
        handleAssignJob,
        handleRelease,
        handleDefinition,
        SwitchChange,
        hasPermission,
      };
    },
  });
</script>
